<script setup lang="ts">
import {reactive, onMounted, nextTick, ref} from 'vue';
import {
  deleteUserList, getUserDataList,
} from '/@/api/api'
import mittBus from '/@/utils/mitt';
import CsvExportor from "csv-exportor";
import {exportExcel} from './exportExcel'
import {ElMessage} from 'element-plus';
import {formatTime} from "/@/utils";
import importTables from '../../components/amxx-table/importTable.vue'
const exportTableRef = ref();
const importTableRef = ref();
const data = reactive({
  title: 'Add',
  dialogShow: false,
  show:false,
  tabIndex: 0,
  dataList: [],
  page: {
    total: 0,
    currentPage: 1,
    pageSize: 10,
  },
  option: {
    searchLabelWidth: 50,
    addBtn: false,
    printBtn: false,
    excelBtn: false,
    // searchSpan: 5,
    searchMenuSpan: 4,
    border: true,
    viewBtn: false,
    editBtn: false,
    delBtn: false,
    align: 'center',
    column: [
      {
        label: 'Start time',
        prop: 'createTime',
        minWidth: 150,
        search: true,
        searchType: 'daterange',
        searchSpan: 12,
        searchLabel: 'Time'
      },
      {
        label: 'First Name',
        prop: 'firstName',
      },
      {
        label: 'Last Name',
        prop: 'lastName',
      },
      {
        label: 'Phone',
        prop: 'userPhone',
      },
      {
        label: 'State',
        prop: 'continent',
      },
      {
        label: 'City',
        prop: 'userCity',
      },
      {
        label: 'Aparment',
        prop: 'userApt',
      },
      {
        label: 'Address',
        prop: 'userAddress',
      },
    ]
  },
  form: {},
  curriculumForm: {},
  id: '',
})

onMounted(() => {
  mittBus.on('usermessageread',() => {
    bannerList()
  })
})

const bannerList = (row: object = {}) => {
  let page = {
    pageIndex: data.page.currentPage,
    pageSize: data.page.pageSize
  }
  getUserDataList({...page, ...row}).then((res: any) => {
    console.log(res)
    if (res.code === 200) {
      data.dataList = res.data.list
      data.page.total = res.data.total
    }
  })
}

const onLoad = (e: any) => {
  console.log(e)
  data.page.currentPage = e.currentPage
  data.page.pageSize = e.pageSize
  bannerList()
}
const refreshChange = () => {
  bannerList()
}
const Delete = (row: any) => {
  data.show = true
  data.id = row.touristId
}
const forbiddenFun = () => {
  deleteUserList({id: data.id}).then((res: any) => {
    bannerList()
    if (res.code === 200) {
      ElMessage({
        showClose: true,
        message: 'The deletion is successful',
        type: 'success',
      })
      data.show = false
    }
  })
}
const resetChange = (item: any) => {
  bannerList()
  data.form = {}
}
const searchChange = (params: any, done: any) => {
  done()
  data.form = {
    startTime: params.createTime ? formatTime(params.createTime[0], 'YYYY-MM-DD') : '',
    endTime: params.createTime ? formatTime(params.createTime[1], 'YYYY-MM-DD') : '',
  }
  bannerList(data.form)
}
const exportBtn = (index:string) => {
  let excelData = []
  const titleArr = ['continent','Name','userAddress','userApt','userCity','Phone','zipCode']
  getUserDataList({pageIndex:index === '0' ? 1 : data.page.currentPage,pageSize: index === '0' ? data.page.total : data.page.pageSize,...data.form}).then((res: any) => {
    console.log(res)
    if (res.code === 200) {
      res.data.list.forEach((item: any) => {
        excelData.push({
          continent: item.continent,
          Name:item.firstName + ',' + item.lastName,
          userAddress: item.userAddress,
          userApt: item.userApt,
          userCity: item.userCity,
          Phone:item.userPhone,
          zipCode: item.zipCode
        })
      })
      excelData.forEach((item: any) => {
        Object.keys(item).forEach((key: any) => {
          if(!titleArr.includes(key)){
            delete item[key]
          }
        })
      })
      const currentDate = new Date();
      const currentYear = currentDate.getFullYear();
      const currentMonth = currentDate.getMonth() + 1 < 10 ? '0' + currentDate.getMonth() + 1: currentDate.getMonth() + 1;
      const currentDay = currentDate.getDate() < 10 ? '0' + currentDate.getDate() : currentDate.getDate();
      CsvExportor.downloadCsv(excelData, { header:titleArr }, `Customer_List_${currentYear}.${currentMonth}.${currentDay}.csv`);
    }
  })
}
</script>

<template>
  <div class="layout-pd">
    <div class="carousel-box">
      <avue-crud ref="exportTableRef" v-model:page="data.page" :data="data.dataList" :option="data.option" @on-load="onLoad"
                 @search-reset="resetChange" @refresh-change="refreshChange" @search-change="searchChange">
        <template #menu="{row}">
          <el-button text type="primary" @click="Delete(row)">Delete</el-button>
        </template>
        <template #menu-right="{}">
          <el-popconfirm width="220" confirm-button-text="Export all data" cancel-button-text="Export the current page"
                         icon="InfoFilled" icon-color="#626AEF" title="Please select an export type"
                         @confirm="exportBtn('0')" @cancel="exportBtn('1')">
            <template #reference>
              <el-button icon="Download" size="default" circle/>
            </template>
          </el-popconfirm>
        </template>
      </avue-crud>
    </div>
    <importTables ref="importTableRef"></importTables>
    <el-dialog v-model="data.show" title="Warning" width="30%">
      <span>Are you sure you want to delete the data?</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.show = false">Cancel</el-button>
          <el-button type="primary" @click="forbiddenFun()">OK</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.carousel-box {
  width: 100%;
  box-sizing: border-box;
  background: var(--el-color-white);
  padding: 20px;
}

.item-img {
  width: 100%;

  img {
    width: 50%;
  }
}

::v-deep .avue-form__row {
  margin-bottom: 20px;
}

::v-deep .el-select {
  width: 100% !important;
}
</style>